package customer.design.dispatcher.dispatchermode.util;

import io.micrometer.core.instrument.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 参数校验工具类
 */
public class ParamsValidUtils {
    /**
     * 校验对象中对应的值是否为空
     *
     * @param param  字段数组
     * @param object 校验对象
     */
    public static void validateParameters(final String[] param, final Object object) {
        Class<?> clazz = object.getClass();
        for (String fieldName : param) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(object);
                if (value == null || value.equals("")) {
                    throw new RuntimeException("请求参数 [" + fieldName + "] 不能为空");
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new RuntimeException("参数校验异常");
            }
        }
    }

    /**
     * 校验对象中对应的值是否为空
     *
     * @param param     字段数组
     * @param paramsMap 校验对象
     */
    public static void validateParameters(final String[] param, final Map<String, Object> paramsMap) {
        for (int i = 0; i < param.length; i++) {
            Object object = paramsMap.get(param[i]);
            if(object==null || StringUtils.isBlank(object.toString())) {
                throw new RuntimeException("请求参数 [" + param[i] + "] 不能为空");
            }
        }
    }
}
